/*
    Android Asynchronous Http Client Sample
    Copyright (c) 2014 Marek Sebera <marek.sebera@gmail.com>
    https://github.com/android-async-http/android-async-http

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.FileAsyncHttpResponseHandler;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;
import com.loopj.ohos.http.ext.LocalHiLog;
import com.loopj.ohos.http.sample.util.FileUtil;

import java.io.File;

import java.io.IOException;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Component;

/**
 * DirectorySample
 */
public class DirectorySample extends SampleParentAbility {
    private static final String LOG_TAG = "DirectorySample";
    private FileAsyncHttpResponseHandler lastResponseHandler = null;
    private Checkbox cbAppend;
    private Checkbox cbRename;

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_directory_sample;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return true;
    }

    @Override
    public String getDefaultURL() {
        return "https://httpbin.org/robots.txt";
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        Button deleteTargetFile = new Button(this);
        deleteTargetFile.setText(ResourceTable.String_button_delete_target_file);
        deleteTargetFile.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                clearOutputs();
                if (lastResponseHandler != null) {
                    File toBeDeleted = lastResponseHandler.getTargetFile();
                    debugResponse(LOG_TAG, String.format(Locale.US, "File was deleted? %b", toBeDeleted.delete()));
                    try {
                        debugResponse(LOG_TAG, String.format(Locale.US, "Delete file path: %s", toBeDeleted.getCanonicalPath()));
                    } catch (IOException e) {
                        LocalHiLog.info(LOG_TAG, e.getMessage());
                    }
                } else {
                    debugThrowable(LOG_TAG, new Error("You have to Run example first"));
                }
            }
        });
        cbAppend = new Checkbox(this);
        cbAppend.setText("Constructor \"append\" is true?");
        cbAppend.setChecked(false);
        cbRename = new Checkbox(this);
        cbRename.setText("Constructor \"renameTargetFileIfExists\" is true?");
        cbRename.setChecked(true);
        customFieldsLayout.addComponent(deleteTargetFile);
        customFieldsLayout.addComponent(cbAppend);
        customFieldsLayout.addComponent(cbRename);
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {
        lastResponseHandler = new FileAsyncHttpResponseHandler(getCacheDir(), cbAppend.isChecked(), cbRename.isChecked()) {
            @Override
            public void onStart() {
                clearOutputs();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File response) {
                debugHeaders(LOG_TAG, headers);
                debugStatusCode(LOG_TAG, statusCode);
                debugFile(response);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                debugHeaders(LOG_TAG, headers);
                debugStatusCode(LOG_TAG, statusCode);
                debugThrowable(LOG_TAG, throwable);
                debugFile(file);
            }

            private void debugFile(File file) {
                if (file == null || !file.exists()) {
                    debugResponse(LOG_TAG, "Response is null");
                    return;
                }
                try {
                    debugResponse(LOG_TAG, file.getCanonicalPath() + "  " + FileUtil.getStringFromFile(file));
                } catch (Throwable t) {
                    LocalHiLog.error(LOG_TAG, "Cannot debug file contents", t);
                }
            }
        };
        return lastResponseHandler;
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
        return client.get(this, URL, headers, null, responseHandler);
    }
}
